import { Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-dialog',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss'],
})
export class DialogComponent implements OnInit {
  @ViewChild('root') root: any;
  @Input() show: Subject<boolean>;

  constructor() {}

  ngOnInit() {
    // 锁定滚动
  }

  ngAfterViewInit(): void {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.

    /* lockScorll */
    if (this.root) {
      const rootElement = this.root?.nativeElement;
      if (rootElement) console.log('root=>', this.root.nativeElement);
      rootElement.addEventListener('touchmove', this.preventDefault);
    }
  }

  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    const root = this.root.nativeElement;
    if (root) root.removeEventListener('touchmove', this.preventDefault);
  }

  preventDefault(event: Event, isStopPropagation?: boolean) {
    /* istanbul ignore else */
    if (typeof event.cancelable !== 'boolean' || event.cancelable) {
      event.preventDefault();
    }

    if (isStopPropagation) {
      this.stopPropagation(event);
    }
  }

  stopPropagation = (event: Event) => event.stopPropagation();
}
